package com.nextcloud.hello.web.controller.config;

import cn.hutool.json.JSONUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Map;

public class LogInterceptor implements HandlerInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(LogInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        if ("GET".equalsIgnoreCase(request.getMethod())) {
            logger.info("Request URI: {}, Method: GET", request.getRequestURI());
        } else if ("POST".equalsIgnoreCase(request.getMethod())) {
            String contentType = request.getContentType();
            if (contentType != null && contentType.contains("application/json")) {
                StringBuilder sb = new StringBuilder();
                BufferedReader reader = request.getReader();
                String line;
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }
                logger.info("Request URI: {}, Method: POST, JSON Parameters: {}", request.getRequestURI(), JSONUtil.toJsonPrettyStr(sb.toString()));
            } else if (contentType != null && contentType.contains("application/x-www-form-urlencoded")) {
                Map<String, String[]> paramMap = request.getParameterMap();
                logger.info("Request URI: {}, Method: POST, Form Parameters: {}", request.getRequestURI(), JSONUtil.toJsonPrettyStr(paramMap));
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        logger.info("Response Status: {}", response.getStatus());
        if (modelAndView != null) {
            Map<String, Object> model = modelAndView.getModel();
            logger.info("Response URI: {}, Return Parameters: {}", request.getRequestURI(), JSONUtil.toJsonPrettyStr(model));
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        if (ex != null) {
            logger.error("Exception occurred: ", ex);
        }
    }
}